package com.googlecode.keepwalking;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class SensorDataFetcher implements SensorEventListener {
	private static final String TAG = "SensorDataFetch";
	private WalkingDetector detector;
	private SensorManager sensorMgr;
	private Sensor sensor;
	private int dataCount;
	private SensorData[] data;
	private int index;
	
	public SensorDataFetcher(WalkingDetector detector) {
		this.detector = detector;
		sensorMgr = (SensorManager)detector.getSystemService(Context.SENSOR_SERVICE);
		sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	}
	
	public void start(int dataCount, int interval) {
		//Log.d(TAG, "start");
		this.dataCount = dataCount;
		data = new SensorData[dataCount];
		index = 0;
		sensorMgr.registerListener(this, sensor, interval);
	}
	
	public void stop() {
		//Log.d(TAG, "stop");
		sensorMgr.unregisterListener(this);
		detector.onData(data, index);
	}
	
	public void onSensorChanged(SensorEvent event) {
		if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			data[index++] = new SensorData(System.currentTimeMillis(), event.values[0], event.values[1], event.values[2]);
			if(index >= dataCount) {
				stop();
			}
		}
	}
	
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

}
